#!/bin/bash
INPUTFILE=$1
OUTPUTFILE="$1.tmp"
PAYLOADFILE=$2
BUTTONPOS=$3
BUTTONCOUNT=0
INSERTPOS=0
LINECOUNT=0

exec 3<&0
exec 0<$INPUTFILE

while read line
do
	LINECOUNT=$(( $LINECOUNT + 1 ))
	TEST=`echo $line | grep -c "</button>"`
	if [ $TEST -gt 0 ]; then
		BUTTONCOUNT=$(( $BUTTONCOUNT + 1 ))
		if [ $BUTTONCOUNT -eq $BUTTONPOS ]; then
			INSERTPOS=$LINECOUNT
		fi
	fi
done

if [ $INSERTPOS -gt 0 ]; then
	head -n $INSERTPOS $INPUTFILE > $OUTPUTFILE
	if [ $? -gt 0 ]; then exit 1; fi

	cat $PAYLOADFILE >> $OUTPUTFILE
	if [ $? -gt 0 ]; then exit 1; fi

	tail -n +$(($INSERTPOS + 1)) $INPUTFILE >> $OUTPUTFILE	
	if [ $? -gt 0 ]; then exit 1; fi

	mv $INPUTFILE $INPUTFILE.bak
	if [ $? -gt 0 ]; then exit 1; fi

	mv $OUTPUTFILE $INPUTFILE
	if [ $? -gt 0 ]; then exit 1; fi


elif [ $BUTTONCOUNT -gt 0 ]; then
	#If the button pos is beyond the button count, rerun to put at the end
	$0 $1 $2 $BUTTONCOUNT
else
	exit 1
fi

exec 0<&3
